import json
import string
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import random
from email.utils import formatdate

import pymysql
import requests
from requests.auth import HTTPBasicAuth
from requests_toolbelt import MultipartEncoder

from Base import Log
from Base.GetYamlFile import getYamlPath

#
# log = Log.Log()
# sql_config = getYamlPath("SqlConfigBasic")
# basic_conn = pymysql.connect(**sql_config)
# cur = basic_conn.cursor()
# select_sql = '''
#         select id from bs_customer where audit_status =0;
# '''
#
# test = cur.execute(select_sql)
#
# test = cur.fetchall()
# base_url = 'http://61.185.114.170:33330/'
# examine_url = base_url + 'tenant-lms-basic-provide/lms/basic/customer/examine'
# header = {
#     'tenant_id': '6042',
#     'type': 'tenant',
#     'refresh_token': '3f9bfa51-e96e-45ee-91ce-a4e0ab8ebb8c',
#     'access_token': '5db94a40-432d-45e9-9fb3-5996fea4be24',
#     'Content-Type': 'application/json',
#     'version': 'middleground-2.5.8-SNAPSHOT'
# }
#
# for item in test:
#     data = {
#         "id": str(item[0]),
#         "auditStatus": 1
#     }
#     result = requests.put(examine_url, json=data, headers=header)
#     log.info(json.loads(str(result.content, 'utf-8')))


# data = [
#     ('tenantId', 1),
#     ('customerId', 30809)
# ]
# data = {'tenantId': 1, 'customerId': 30809}
#
# data1 = [('tenantId', "1"), ('customerId', "30809")]
#
# m = MultipartEncoder(fields=data1)
# headers = {
#     'tenant_id': '1',
#     'type': 'tenant',
#     'refresh_token': '98701d4b-9ca8-466f-ad8d-347c2e895254',
#     'access_token': 'bfe7f2b3-c609-426e-a0ef-25ff13b19895',
# }
#
# result = requests.post("http://192.168.17.236:30510/tenant-lms-account-provide/capitalAccount/accountList",
#                        files=m,
#                        headers=headers)
# print(str(result.content, 'utf-8'))

# 准备要发送的数据（非文件字段），确保值都是字符串
# 准备要发送的数据（非文件字段）
url = "http://192.168.17.236:30510/tenant-lms-account-provide/capitalAccount/accountList"
url1 = "http://192.168.17.236:30510/tenant-lms-account-provide/capitalAccount/list"

payload = [("tenantId", int(1)), ("customerId", 30809)]
data = {'tenantId': '1',
        'customerId': '30809'}
data1 = {
    "customerId": 30809,
    "type": 1,
    "accessId": 125167893229637
}
files = [
]
headers = {
    'access_token': 'bfe7f2b3-c609-426e-a0ef-25ff13b19895',
    'refresh_token': '98701d4b-9ca8-466f-ad8d-347c2e895254',
    'tenant_id': '1',
    'type': 'tenant'
}
paramsTest = {
    "paramsTest": "paramsTest"
}
formDataTest = {"formDataTest": "formDataTest"}

# response = requests.request("POST", url1, headers=headers, data=data1)
# paramsTestResponse = requests.request("POST", "http://localhost:9001/paramsTest", data=paramsTest)
# formDataTestResponse = requests.request("POST", "http://localhost:9001/formDataTest", data=formDataTest)
# accountListResponse = requests.request("POST", "http://localhost:9001/accountList", data=data)

# print(paramsTestResponse.text)
# print(formDataTestResponse.text)
# print(accountListResponse.text)
# print(response.text)

# 创建一个Session对象
session = requests.Session()

# 准备URL和认证信息（如果需要的话）
# url = 'http://example.com/post'
# auth = HTTPBasicAuth('user', 'pass')  # 如果需要的话

# 手动创建multipart/form-data
# boundary = ''.join(random.choices(string.ascii_letters + string.digits, k=30))
multipart_form_data = MIMEMultipart('form-data')

# 设置其他头部信息（可选）
multipart_form_data['Date'] = formatdate(localtime=True)

# MIMEMultipart对象在内部设置了Content-Type头部，并自动添加了boundary参数
# 我们可以通过检查Content-Type头部来获取boundary值
content_type = multipart_form_data.get('Content-Type')
print(content_type)
# Content-Type头部类似于"multipart/form-data; boundary=XXXXXXXXXX"
# 我们需要解析这个字符串来提取boundary值
_, boundary_param = content_type.split('; ', 1)
boundary_value = boundary_param.split('=')[1].strip('"')

# 打印boundary值
print(f"自动生成的boundary值: {boundary_value}")
# print(multipart_form_data.get('Content-Type'))
# print(multipart_form_data)
# 添加字段
part = MIMEText('1')
part.add_header('Content-Disposition', 'form-data; name="tenantId"')
multipart_form_data.attach(part)

part = MIMEText('30809')
part.add_header('Content-Disposition', 'form-data; name="customerId"')
multipart_form_data.attach(part)
# print(multipart_form_data.get_content_type())
# 将MIMEMultipart对象转换为字节流
body = multipart_form_data.as_bytes()

# 构造请求头，包括Content-Type和boundary
# content_type = f'multipart/form-data; boundary={boundary}'
# headers["Content-Type"] = content_type
# print(multipart_form_data.as_string())
# print(headers)
# 创建Request对象
# req = requests.request('POST', url, headers=headers, data=multipart_form_data.as_string())

# 使用Session发送请求
# prepared_request = session.prepare_request(req)
# response = session.send(prepared_request)

# 打印响应内容
# print(req.text)
